﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLZJFurnitureSCM.BLL;
using QLZJFurnitureSCM.Model;
using System.Text.RegularExpressions;

namespace QLZJFurnitureSCM.WinForm
{
    public partial class FrmEmployee : Form
    {
        private EmployeeService employeeService = null;
        private List<Employee> lstEmployee = null;

        public FrmEmployee()
        {
            InitializeComponent();
            employeeService = new EmployeeService();
        }

        private void FrmEmployee_Load(object sender, EventArgs e)
        {
            lstEmployee = employeeService.FindAllEmployee();
            //DateTime chkOut;
            decimal totalMonthPay = 0M;
            foreach (Employee employee in lstEmployee)
            {
                //if (string.IsNullOrEmpty(employee.EmployeeDateCheckOut))
                //    chkOut = DateTime.Parse(employee.EmployeeDateCheckOut);
                dataGridViewEmployee.Rows.Add(new object[] { 
                           employee.EmployeeId
                          ,employee.EmployeeName
                          ,employee.EmployeeSex
                          ,employee.EmployeeAge
                          ,employee.EmployeePID
                          ,employee.EmployeeDateCheckIn
                          ,employee.EmployeePayNow
                          ,employee.EmployeeCanDrive
                          ,employee.EmployeePhone
                          ,employee.EmployeeAddress
                    /*
                    employee.EmployeeId,
                    employee.EmployeeName,
                    employee.EmployeePID,
                    employee.EmployeeDateCheckIn,
                    //employee.EmployeeDateCheckOut,//chkOut,
                    employee.EmployeePayNow,
                    employee.EmployeeCanDrive*/
                });
                totalMonthPay += employee.EmployeePayNow;
            }

            string chs = ConvertToChinese(totalMonthPay);

            this.toolStripStatusLabelFrmEmployee.Text = string.Format("共有员工 {0} 名, 每月需支付薪共 {1} 元, 合 {2} .", lstEmployee.Count, totalMonthPay.ToString("C"), chs);
        }

        private string ConvertToChinese(decimal x)
        {
            string s = x.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
            string d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
            return Regex.Replace(d, ".", delegate(Match m) { return "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟萬億兆京垓秭穰"[m.Value[0] - '-'].ToString(); });
        }

        private void dataGridViewEmployees_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void FrmEmployee_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (this.needUpdate)
            //{
                //if (!this.hasUpdate)
                //{
                    DialogResult result = MessageBox.Show("数据已更改, 是否在离开前更新到数据库?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (DialogResult.Yes == result)
                    {
                        //this.employeesTableAdapter.Update(this.furnitureDataSet.Employees);
                    }
                //}
            //}
        }

        private object ObjSave = null;

        private void dataGridViewEmployees_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            ObjSave = dataGridViewEmployee[e.ColumnIndex, e.RowIndex].Value;
            //this.needUpdate = true;
        }

        private void dataGridViewEmployees_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell currentCell = dataGridViewEmployee[e.ColumnIndex, e.RowIndex];
            string columnName = dataGridViewEmployee.Columns[e.ColumnIndex].Name;
            if ("employeeDateCheckIn".Equals(columnName) || "employeeDateCheckOut".Equals(columnName))
            {
                if (!ValidateDateFormat(currentCell))
                {
                    MessageBox.Show("请输入一个有效日期, 格式如:2011-8-8", "错误");
                    return;
                }
            }
            if (!currentCell.Value.ToString().Equals(ObjSave.ToString()))
            {
                currentCell.Style.ForeColor = Color.Red;
                //this.needUpdate = true;
                //this.hasUpdate = false;
            }
        }

        private bool ValidateDateFormat(DataGridViewCell currentCell)
        {
            DateTime result;
            if (!DateTime.TryParse(currentCell.Value.ToString(), out result))
                return false;
            return true;
        }

        private void dataGridViewEmployees_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show("leave");
        }

        private void dataGridViewEmployees_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            //MessageBox.Show("parsing");
            DateTime result;
            string columnName = dataGridViewEmployee.Columns[e.ColumnIndex].Name;
            if ("employeeDateCheckInDataGridViewTextBoxColumn".Equals(columnName) || "employeeDateCheckOutDataGridViewTextBoxColumn".Equals(columnName))
            {
                if (!DateTime.TryParse(e.Value.ToString(), out result))
                {
                    MessageBox.Show("请输入一个有效日期, 格式如:2011-8-8", "错误");
                    return;
                }
            }
        }

        private void dataGridViewEmployees_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

            //MessageBox.Show("error:{0}", e.Exception.Message);
        }

        private void dataGridViewEmployees_Paint(object sender, PaintEventArgs e)
        {
            for (int i = 0; i < this.dataGridViewEmployee.Rows.Count; )
            {
                this.dataGridViewEmployee.Rows[i].DefaultCellStyle.BackColor = SystemColors.ActiveBorder;//System.Drawing.Color.FromArgb(86, 172, 210);
                i += 2;
            }
        }

        //////////////////////////////////////////////////////////////////////////

        private void btnOperator_Click(object sender, EventArgs e)
        {
            //if failure, hide panel
            string eName = this.txtEmployeeName.Text;
            string ePhone = this.txtEmployeePhone.Text;
            string eAddr = this.txtEmployeeAddr.Text;
            string eMonthDay = this.txtMonthPay.Text;
            string ePID = this.txtPID.Text;
            string eAge = this.txtAge.Text;
            string eGender = this.rdoMale.Checked ? "男" : "女";
            bool eCanDrive = this.chkCanDrive.Checked;
            DateTime dateChkIn = this.dateTimePickerCheckIn.Value;

            Employee employee = new Employee();
            employee.EmployeeName = eName;
            employee.EmployeePhone = ePhone;
            employee.EmployeeAddress = eAddr;
            employee.EmployeePayNow = decimal.Parse(eMonthDay);
            employee.EmployeePID = ePID;
            employee.EmployeeAge = int.Parse(eAge);
            employee.EmployeeSex = eGender;
            employee.EmployeeCanDrive = eCanDrive;
            employee.EmployeeDateCheckIn = dateChkIn;

            if (this.btnEmployeeModify.Enabled)
            {
                int employeeId = int.Parse(this.lbEmployeeId.Text);
                employee.EmployeeId = employeeId;
                //if the MonthPay had change, add a record into EmployeePayChange.
                if (employeeService.Update(employee))
                {
                    this.toolStripStatusLabelOP.Text = "更新成功";
                    this.panelOP.Visible = false;
                }
                else
                    this.toolStripStatusLabelOP.Text = "更新失败, 请修改重试.";
            }
            else
            {
                int count = (from emp in lstEmployee where emp.EmployeeName.Equals(EmployeeName) || emp.EmployeePID.Equals(ePID) select emp).Count();
                if (count == 0)
                {
                    if (employeeService.Insert(employee).EmployeeId > 0)
                    {
                        this.toolStripStatusLabelOP.Text = "新增成功";
                        this.panelOP.Visible = false;
                    }
                    else
                        this.toolStripStatusLabelOP.Text = "新增失败, 请修改重试.";
                }
                else
                    this.toolStripStatusLabelOP.Text = "姓名或身份证不能重复添加, 请修改重试.";

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = false;
            this.btnEmployeeNew.Enabled = true;
            this.btnEmployeeDelete.Enabled = true;
            this.btnEmployeeModify.Enabled = true;
        }

        #region EmployeNew, Delete, Modify
        private void btnEmployeeNew_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = true;
            this.txtEmployeeName.Text = "";
            this.txtEmployeePhone.Text = "";
            this.txtEmployeeAddr.Text = "";
            this.txtMonthPay.Text = "";
            this.txtPID.Text = "";
            this.txtAge.Text = "";
            this.rdoMale.Checked = true;
            this.chkCanDrive.Checked = false;
            this.dateTimePickerCheckIn.Value = DateTime.Now;
            this.txtEmployeeName.ReadOnly = false;
            this.btnEmployeeModify.Enabled = false;
            this.btnEmployeeDelete.Enabled = false;
        }

        private void btnEmployeeDelete_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewEmployee.SelectedRows.Count == 0)
                return;
            if (DialogResult.Yes == MessageBox.Show(this, "确认删除此员工所有信息?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                List<Employee> lstEmployeeDel = new List<Employee>();
                Employee employee = null;
                foreach (DataGridViewRow row in this.dataGridViewEmployee.SelectedRows)
                {
                    employee = new Employee();
                    employee.EmployeeId = int.Parse(row.Cells["EmployeeId"].Value.ToString());
                    lstEmployeeDel.Add(employee);
                }
                if (employeeService.DeleteBatch(lstEmployeeDel))
                    this.toolStripStatusLabelOP.Text = "删除成功.";
                else
                    this.toolStripStatusLabelOP.Text = "删除失败.";
                //应该另起线程造作, 以免数据量.
                lstEmployee = employeeService.FindAllEmployee();
                dataGridViewEmployee.Rows.Clear();
                foreach(Employee emp in lstEmployee)
                {
                    dataGridViewEmployee.Rows.Add(new object[] { 
                            emp.EmployeeId
                          ,emp.EmployeeName
                          ,emp.EmployeeSex
                          ,emp.EmployeeAge
                          ,emp.EmployeePID
                          ,emp.EmployeeDateCheckIn
                          ,emp.EmployeePayNow
                          ,emp.EmployeeCanDrive
                          ,emp.EmployeePhone
                          ,emp.EmployeeAddress
                    });
                }
                //dataGridViewEmployee.DataSource = lstEmployee;
            }
        }

        private void btnEmployeeModify_Click(object sender, EventArgs e)
        {
            this.panelOP.Visible = true;
            DataGridViewRow selectRow = null;

            if (this.dataGridViewEmployee.SelectedRows.Count > 0)
            {
                selectRow = this.dataGridViewEmployee.SelectedRows[0];
                this.lbEmployeeId.Text = selectRow.Cells["EmployeeId"].Value.ToString();
                this.txtEmployeeName.Text = selectRow.Cells["EmployeeName"].Value.ToString();
                this.txtEmployeePhone.Text = selectRow.Cells["EmployeePhone"].Value.ToString();
                this.txtEmployeeAddr.Text = selectRow.Cells["EmployeeAddress"].Value.ToString();
                this.txtMonthPay.Text = selectRow.Cells["EmployeePayNow"].Value.ToString();
                this.txtPID.Text = selectRow.Cells["EmployeePID"].Value.ToString();
                this.txtAge.Text = selectRow.Cells["EmployeeAge"].Value.ToString();
                string gender = selectRow.Cells["EmployeeSex"].Value.ToString();
                this.dateTimePickerCheckIn.Value = DateTime.Parse(selectRow.Cells["EmployeeDateCheckIn"].Value.ToString());
                if ("女".Equals(gender))
                    this.rdoFemale.Checked = true;
                else
                    this.rdoMale.Checked = true;
                this.chkCanDrive.Checked = bool.Parse(selectRow.Cells["EmployeeCanDrive"].Value.ToString());

                this.txtEmployeeName.ReadOnly = true;
                this.btnEmployeeNew.Enabled = false;
                this.btnEmployeeDelete.Enabled = false;
            }
            else
                MessageBox.Show("请先在员工列表里选择要修改的员工.", "提示");
        }
        #endregion

        #region KeyPress event Hnadle
        private void txtMonthPay_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.LastIndexOf('.') != -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
        }

        private void txtMonthPay_Leave(object sender, EventArgs e)
        {
            decimal result;
            if (!decimal.TryParse(this.txtMonthPay.Text, out result))
            {
                MessageBox.Show("请输入有效的薪酬数值, 如12345678.9", "错误");
                this.txtMonthPay.Focus();
                this.txtMonthPay.SelectAll();
            }
        }

        private void txtPID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && e.KeyChar != 'X' && e.KeyChar != 'x' && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtEmployeePhone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar == '-')
                {
                    if (((TextBox)sender).Text.LastIndexOf('-') != -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
        }
        #endregion
    }
}
